package com.dyh.quickdemo.demos.esshutdown;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
@Author=Joey Wheeler
@Date=2020/10/23 10:33
*/

/*
            shutdown   shutdownNow
死循环型      no          no
时钟周期型    no          ok
阻塞型        no          ok

*/
@RestController("/es")
@Slf4j
public class EsShutdownController {

    ExecutorService executorService = Executors.newFixedThreadPool(3);

    Object lock =new Object();

    @GetMapping("/shutDownMugen")
    public void shutDownMugen(){
        executorService.submit(()->{
            while (true){
                log.info("mugen");
            }
        });
        /*
        无限循环关不了
        2020-10-23 10:37:08.636  INFO 23932 --- [pool-1-thread-1] c.d.q.d.esshutdown.EsShutdownController  : mugen
2020-10-23 10:37:08.636  INFO 23932 --- [pool-1-thread-1] c.d.q.d.esshutdown.EsShutdownController  : mugen

        workers.size = 1
        completedTaskCount = 0
        */
        executorService.shutdownNow();
        System.out.println();
    }

    @GetMapping("/clock")
    public void clock(){
        executorService.submit(()->{
            while (true){
                log.info("startSleep");
                Thread.sleep(2000L);
                log.info("endSleep");
            }
        });

        System.out.println();

        /*
        shutdownNow
         works.size = 0
         completedTaskCount = 0
         没有打印 endSleep;
        */
    }



    @GetMapping("/toWait")
    public void toWait(){
        /*不用*executorService req 会被卡住*/
        executorService.submit(()->{
            synchronized (lock){
                try {
                    log.info("wait前");
                    lock.wait();
                } catch (InterruptedException e) {
                    log.error("e=",e);
                }
                log.info("after wait ");
            }
        });

    }
    /*  works.size = 1
         completedTaskCount = 0*/

    /*
    * works.size = 0
     completedTaskCount = 0
    * InterruptedException
    * after wait
    * */

    /*关掉后 RejectedExecutionException*/

    @GetMapping("/shutdown")
    public void shutdown(){
        executorService.shutdown();
        System.out.println();

    }

    @GetMapping("/shutdownNow")
    public void shutdownNow(){
        executorService.shutdownNow();
        System.out.println();
    }

    @GetMapping("/toNotify")
    public void toNotify(){
        executorService.submit(()->{
            synchronized (lock){
                lock.notify();
                log.info("调用notify");
            }
        });

    }


}
